export function getLocalConfig() {
  const config = wx.getStorageSync('g150')
  // console.log('get g150', config)
  if (config === '') {
    const default_config = {
      step: 0,
      process: initLocalConfig()
    }
    // console.log('g150 default config', default_config)
    setLocalConfig(default_config)
    return default_config
  }

  return JSON.parse(config)
}

export function setLocalConfig(config) {
  console.log('g150 save config')
  wx.setStorageSync('g150', JSON.stringify(config))
}

function initLocalConfig() {
  const process = []
  const plugin_config = wx.getStorageSync('pageConfig').plugin.g150  // TODO:可能会出错

  let profile = {}
  let riddle_count = 0
  let riddle_index = 0

  // step 0
  process.push(default_process)

  // step 1（编码）
  profile = encodeProfile(plugin_config.type1)
  process.push({
    input: profile.input_word,
    table: profile.table,
    key: profile.key,
    output: profile.output_word,
    answer: '',
    prompt: profile.prompt,
    operation: ''
  })

  // step 2（解码）
  profile = encodeProfile(plugin_config.type1)
  process.push({
    input: profile.output_word,
    table: profile.table,
    key: profile.key,
    output: profile.input_word,
    answer: '',
    prompt: profile.prompt,
    operation: ''
  })

  // step 3
  process.push(default_process)

  // step 4（穷尽法解码）
  profile = encodeProfile(plugin_config.type2)
  process.push({
    input: profile.output_word,
    table: profile.table,
    key: profile.key,
    output: profile.input_word,
    answer: '',
    prompt: profile.prompt,
    operation: ''
  })

  // step 5 (中文解码)
  riddle_count = plugin_config.type3.length
  riddle_index = Math.floor(Math.random() * riddle_count)
  profile = encodeProfile(plugin_config.type3[riddle_index])
  process.push({
    input: profile.output_word,
    table: profile.table,
    key: profile.key,
    output: profile.input_word,
    answer: '',
    prompt: profile.prompt,
    operation: plugin_config.operation[0]    // 需要执行晋级书
  })

  // step 6（随机提取一道题目，终极题目）
  riddle_count = plugin_config.type4.length
  riddle_index = Math.floor(Math.random() * riddle_count)
  profile = encodeProfile(plugin_config.type4[riddle_index])
  process.push({
    input: profile.output_word,
    table: profile.table,
    key: profile.key,
    output: profile.input_word,
    answer: '',
    prompt: profile.prompt,
    operation: ''
  })

  // step 7
  process.push({
    input: profile.output_word,
    table: profile.table,
    key: profile.key,
    output: profile.input_word,
    answer: '',
    prompt: profile.prompt,
    operation: plugin_config.operation[1]    // 执行晋级书，打开最后一关
  })

  // step 8（最后）
  process.push({
    input: profile.output_word,
    table: profile.table,
    key: profile.key,
    output: profile.input_word,
    answer: '',
    prompt: profile.prompt,
    operation: ''
  })
  // console.log('init config', process)
  return process
}

function encodeProfile(profile) {
  const wordTable = profile.table
  const keyword_list = profile.input
  const wordTableLength = wordTable.length
  const index = Math.floor(Math.random() * keyword_list.length)
  const key = Math.floor(Math.random() * (wordTableLength - 6)) + 5 // 至少偏移5个字符
  // const key = 26
  const input_word = keyword_list[index]
  let output_word = ''

  // console.log('input', input_word)
  // console.log('key', key)
  for (let index = 0; index < input_word.length; index++) {
    const char = input_word[index]
    if (char === ' ') {
      output_word += ' '
    } else {
      const pos = wordTable.indexOf(char)
      const new_pos = (pos + key) % wordTableLength
      const new_char = wordTable[new_pos]
      if (pos < 0) {
        console.log(char, pos, new_pos, new_char)
      }
      output_word += new_char
    }
  }

  profile.input_word = input_word
  profile.output_word = output_word
  profile.key = key

  return {
    input_word: input_word,
    table: wordTable,
    key: key,
    output_word: output_word,
    answer: '',
    prompt: profile.tip,
    operation: ''
  }
}

const default_process = {
  input: '',
  table: '',
  key: 0,
  output: '',
  answer: '',
  prompt: '',
  operation: ''
}

const plugin_config = {
	"g150": {
		"name": "凯撒密码",
		"type1": {
			"input": [
				"mobile",
				"phone",
				"input",
				"world",
				"space",
				"dying",
				"utter",
				"going",
				"there",
				"upper",
				"great",
				"crazy",
				"build",
				"taste",
				"loops",
				"where"
			],
			"table": "abcdefghijklmnopqrstuvwxyz"
		},
		"type2": {
			"input": [
				"SHE SINGS BEAUTIFULLY",
				"THEY DANCED TO THE MUSIC",
				"I WANT TO GO HOME",
				"HE LIKES EATING PIZZA",
				"THEY WON THE GAME",
				"HE WILL MAKE NOISE",
				"SHE CANNOT FIND IT",
				"MISSION FAILED AGAIN",
				"SUSAN CAN HANDLE",
				"TEACHER IN RETREAT",
				"COMMANDER ARRIVE",
				"GO TO BACK DOOR NOW",
				"NOTHING LEFT HERE",
				"RABBIT COMING SOON",
				"CODE IS GRANDPAS",
				"WATCH OUT DANGER"
			],
			"table": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		},
		"type3": [
			{
				"input": [
					"浮图关"
				],
				"table": "渝城三面浮江陆路惟图抱一线壁立万仞关磴曲千层"
			},
			{
				"input": [
					"洪崖洞"
				],
				"table": "可望吊脚洞群楼观渝文洪滴翠逛山城崖老街赏巴化美食"
			}
		],
		"type4": [
			{
				"input": [
					"浮图关"
				],
				"table": "该孚雕艺术作品位于险峻的浮图关峭壁之上旁有环公园",
				"tip": "第13行"
			},
			{
				"input": [
					"渝中半岛"
				],
				"table": "核心吊脚楼在渝中半岛的崖整上成群丛生屋舍连绵山城",
				"tip": "第13行"
			}
		],
		"operation": [
			"H02;H03;H07;H08;H09;H12;S10;",
			"H01;H04;H05;H06;S13"
		]
	}
}